package cn.edu.sgu.www.mhxysy.shiro.filter;

import cn.edu.sgu.www.mhxysy.consts.MimeTypes;
import cn.edu.sgu.www.mhxysy.restful.JsonResult;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 定义PermsFilter过滤器（覆盖shiro的perms过滤器）
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
public class PermsFilter extends PermissionsAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws IOException {
        boolean accessAllowed = super.isAccessAllowed(req, resp, mappedValue);

        // 处理未授权
        if (!accessAllowed) {
            // 获取HttpServletRequest对象
            HttpServletRequest request = (HttpServletRequest) req;
            // 得到请求地址
            String requestURI = request.getRequestURI();
            String message = "正在访问未授权的资源：" + requestURI;

            log.debug(message);

            // 定义响应时状态码
            ResponseCode responseCode = ResponseCode.UNAUTHORIZED;

            // 获取HttpServletResponse对象
            HttpServletResponse response = (HttpServletResponse) resp;

            response.reset();
            response.setStatus(responseCode.getValue());
            response.setContentType(MimeTypes.APPLICATION_JSON_CHARSET_UTF_8);

            try (ServletOutputStream outputStream = response.getOutputStream()) {
                // 构建返回对象
                JsonResult<Void> jsonResult = JsonResult.error(responseCode, message);

                // 转为JSON字符串
                String jsonString = JSON.toJSONString(jsonResult);

                // 将JSON字符串转为字节数组
                byte[] data = jsonString.getBytes(StandardCharsets.UTF_8);

                outputStream.write(data);
            }
        }

        return true; // 返回true，阻止shiro继续处理未授权
    }

}